const { formatFileSize, calculateSpeed } = require('./utils');

/**
 * 进度监控类
 * @class ProgressMonitor
 */
class ProgressMonitor {
    /**
     * 构造函数
     * @param {DownloadManager} downloadManager - 下载管理器实例
     */
    constructor(downloadManager) {
        this.downloadManager = downloadManager;
        this.tasks = new Map();
        this.interval = null;
        this.updateFrequency = 500; // 更新频率(毫秒)
    }

    /**
     * 开始监控
     */
    start() {
        if (this.interval) return;

        this.interval = setInterval(() => {
            this.displayProgress();
        }, this.updateFrequency);

        this.displayProgress();
    }

    /**
     * 停止监控
     */
    stop() {
        if (this.interval) {
            clearInterval(this.interval);
            this.interval = null;
        }
    }

    /**
     * 添加任务到监控
     * @param {string} taskId - 任务ID
     * @param {DownloadTask} task - 下载任务实例
     */
    addTask(taskId, task) {
        this.tasks.set(taskId, task);
    }

    /**
     * 从监控中移除任务
     * @param {string} taskId - 任务ID
     */
    removeTask(taskId) {
        this.tasks.delete(taskId);
    }

    /**
     * 显示进度信息
     */
    displayProgress() {
        console.clear();
        console.log('=== LenDownload 下载进度监控 ===');
        console.log(`全局状态: 总任务数 ${this.downloadManager.queue.length} | 运行中 ${this.downloadManager.activeDownloads.size} | 已完成 ${this.downloadManager.completedDownloads.length}`);

        if (this.downloadManager.globalSpeedLimit > 0) {
            console.log(`全局限速: ${formatFileSize(this.downloadManager.globalSpeedLimit)}/s`);
        }

        console.log('--------------------------------');

        this.tasks.forEach((task, taskId) => {
            const statusMap = {
                'pending': '等待中',
                'downloading': '下载中',
                'paused': '已暂停',
                'completed': '已完成',
                'failed': '失败',
                'stopped': '已停止'
            };

            console.log(`[任务ID: ${taskId}]`);
            console.log(`状态: ${statusMap[task.status] || task.status}`);
            console.log(`进度: ${task.progress.toFixed(2)}% (${formatFileSize(task.downloadedBytes)}/${formatFileSize(task.totalBytes)})`);
            console.log(`速度: ${task.speed}`);

            if (task.options.speedLimit > 0) {
                console.log(`限速: ${formatFileSize(task.options.speedLimit)}/s`);
            }

            console.log('--------------------------------');
        });
    }
}

module.exports = ProgressMonitor;